<template>
  <div class="dept-user-page">

    <div class="back-box">
      <span @click="backPageHandle" class="back-page"><i class="el-icon-back"></i>返回</span>
      <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
      <span>{{ `管理部门用户（${deptName}）` }}</span>
    </div>

    <!-- 已关联用户 start   -->
    <transition name="el-zoom-in-top">
      <el-form v-show="deptUserParams.searchDeptUserVisible" inline size="mini" :model="searchDeptUserForm" ref="searchDeptUserForm" @keyup.enter.native="searchDeptUserHandle">
        <el-form-item label="已关联用户">
          <el-input v-model="searchDeptUserForm.word" clearable placeholder="请选择检索的用户名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button :disabled="deptUserLoading" @click="searchDeptUserHandle" type="primary"
                     icon="el-icon-search">查询</el-button>
        </el-form-item>
      </el-form>
    </transition>

    <div class="d-u-tool">
      <el-button :disabled="deptUserLoading" @click="$refs.userDialog.initUserDialog(deptId, deptName, undefined, false)"
                 type="primary" size="mini" plain icon="el-icon-plus">添加</el-button>
      <el-button :disabled="deptUserLoading || deptUserSelection.length === 0" @click="deleteUserHandle(undefined)"
                 type="danger" size="mini" plain icon="el-icon-delete">删除</el-button>

      <!-- 还差一个刷新表格事件 -->
      <right-tool-bar :search-visible="deptUserParams.searchDeptUserVisible" :search-load="deptUserLoading"
                      @toggle-search="deptUserParams.searchDeptUserVisible = !deptUserParams.searchDeptUserVisible" @refresh-table="getDeptUserList" />
    </div>

    <el-table
      highlight-current-row
      v-loading="deptUserParams.dataLoad"
      element-loading-text="可关联用户数据加载中..."
      element-loading-spinner="el-icon-loading"
      :data="deptUserList"
      @selection-change="(val) => this.deptUserSelection = val"
      row-key="userId"
      ref="deptUserTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="username" header-align="center" align="center" label="用户名称"></el-table-column>
      <el-table-column prop="phone" header-align="center" align="center" label="手机号"></el-table-column>
      <el-table-column prop="email" header-align="center" align="center" label="邮箱号"></el-table-column>
      <el-table-column prop="loginName" header-align="center" align="center" label="登录别名"></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态">
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 0 ? 'primary' : 'danger'">
            {{ scope.row.status === 0 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="关联时间" width="135"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="创建用户"></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        width="150"
        label="操作">
        <template v-slot="scope">

          <el-button type="text" icon="el-icon-s-operation" size="small"
                     @click="$refs.userRoleModifyDialog.initUserRoleModifyDialog(scope.row)">
            角色
          </el-button>
          <el-button type="text" icon="el-icon-delete" size="small" @click="deleteUserHandle(scope.row)"
                     class="danger-color">删除</el-button>


        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="deptUserTableSizeChangeHandle"
      @current-change="deptUserTableCurrentChangeHandle"
      :current-page="deptUserParams.pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="deptUserParams.pageSize"
      :total="deptUserParams.totalNum"
      layout="total, sizes, prev, pager, next, jumper"
      class="paging">
    </el-pagination>
    <!-- 已关联用户 end -->

    <!-- 用户信息操作弹出框 -->
    <user-save-update ref="userDialog" @close-dialog="closeUserDialogHandle" />

    <!-- 用户关联角色弹出框 -->
    <user-role-modify ref="userRoleModifyDialog" />
  </div>
</template>

<script>
  import RightToolBar from '@/components/common/right-toolbar';
  import UserSaveUpdate from "@/components/user/save-update";
  import UserRoleModify from "@/components/role/role-user/modify.vue";

  export default {
    layout: 'admin',
    name: "admin-system-dept-user",
    components: { RightToolBar, UserSaveUpdate, UserRoleModify },
    data() {
      return {
        // 部门id
        deptId: undefined,
        // 部门名称
        deptName: undefined,
        // 部门已关联用户列表
        deptUserList: [],
        // 部门已关联用户被选中的行
        deptUserSelection: [],
        // 用户检索表单对象
        searchDeptUserForm: {
          // 用户名称
          word: '',
        },
        // 已关联用户相关参数
        deptUserParams: {
          // 数据是否加载[false-不加载 true-加载]
          dataLoad: false,
          // 按钮是否可被点击[false-可以被点击 true-不可被点击]
          buttonLoad: false,
          // 已关联用户检索表单是否显示
          searchDeptUserVisible: true,
          // 当前展示页码
          pageIndex: 1,
          // 当前页显示个数
          pageSize: 10,
          // 已关联用户数量
          totalNum: 0,
        },
      }
    },
    computed: {
      // 主题颜色
      themeColor() {
        return this.$store.state.settings.theme
      },
      // 已关联用户数据加载中
      deptUserLoading() {
        let deptUserParams = this.deptUserParams
        return deptUserParams.dataLoad || deptUserParams.buttonLoad
      },

    },
    created() {
      if (process.client) {
        let query = this.$route.query
        if (!query.dept || !query.deptName) {
          this.$router.push('/admin/system/dept')
        }
        this.deptId = query.dept
        this.deptName = query.deptName

        this.getDeptUserList()
      }
    },
    methods: {
      /**
       * 回到部门管理页面事件
       */
      backPageHandle() {
        this.$router.push({ name: 'admin-system-dept' })
      },
      /**
       * 检索已关联用户列表事件
       */
      searchDeptUserHandle() {
        this.deptUserParams.pageIndex = 1;

        this.getDeptUserList();
      },
      /**
       * 获取已关联用户列表方法
       */
      getDeptUserList() {
        let deptUserParams = this.deptUserParams;
        let searchDeptUserForm = this.searchDeptUserForm;
        let formObj = {
          deptId: this.deptId,
          word: searchDeptUserForm.word,
          page: deptUserParams.pageIndex,
          limit: deptUserParams.pageSize
        }
        // 表格数据加载
        deptUserParams.dataLoad = true
        this.$axios.$post('/sys/dept-user/page/list', formObj)
          .then(({ data:page }) => {
            this.deptUserList = page.list
            deptUserParams.totalNum = page.totalNum

          })
          .catch(() => {})
          .finally(() => {
            // 表格加载结束
            deptUserParams.dataLoad = false
          })
      },
      /**
       * 已关联用户表格显示个数变化事件
       * @param {Number} val 最新显示个数
       */
      deptUserTableSizeChangeHandle(val) {
        this.deptUserParams.pageSize = val
        this.deptUserParams.pageIndex = 1
        this.getDeptUserList()
      },
      /**
       * 已关联用户表格页码变化事件
       * @param {Number} val 最新页码
       */
      deptUserTableCurrentChangeHandle(val) {
        if (this.deptUserParams.pageIndex === val) {
          return
        }
        this.deptUserParams.pageIndex = val
        this.getDeptUserList()
      },
      /**
       * 删除用户事件
       * @param {Object} deptUser 用户对象（只有单个删除时，该参数才有值）
       */
      deleteUserHandle(deptUser) {
        // 所有要删除的用户id
        let userIds = []
        // 所有要删除的用户名字
        let userName = []
        if (!deptUser) {
          this.deptUserSelection.forEach(user => {
            userIds.push(user.userId);
            userName.push(user.username);
          })
        } else {
          userIds.push(deptUser.userId);
          userName.push(deptUser.username);
        }

        this.$confirm(`确定删除‘${userName}’用户吗?`, '删除提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 按钮不可被点击
          this.dataLoad = true
          this.$axios.$delete('/sys/user/delete', { data: userIds })
            .then(() => {
              this.notify('success', '操作成功', `${userName}用户删除成功`);

              // 重新获取角色列表
              this.getDeptUserList()
            })
            .catch(() => {})
            .finally(() => {
              // 按钮恢复可点击
              this.dataLoad = false
            })

        }).catch(() => {})
      },
      /**
       * 关闭用户操作弹出框事件
       * @param {boolean} bool 是否刷新表格数据
       */
      closeUserDialogHandle(bool) {
        if (bool) {
          this.getDeptUserList()
        }
      },
    }
  }
</script>

<style scoped>
  .dept-user-page .back-box {
    font-size: 14px;
    height: 35px;
    line-height: 35px;
    margin-bottom: 7px;
  }
  .back-box .back-page {
    height: 100%;
    cursor: pointer
  }
  .back-box .back-page:hover {
    background-color: #F2F6FC;
  }
  .dept-user-page .d-u-tool {
    line-height: 35px;
    margin-bottom: 7px;
  }
  .dept-user-page .d-u-tool .dept-leader {
    display: inline-block;
    font-size: 14px;
    margin-left: 20px;
  }
  .dept-user-page .d-u-tool .dept-leader .delete-leader {
    margin-left: 7px;
    display: none;
  }
  .dept-user-page .d-u-tool .dept-leader:hover .delete-leader {
    display: inline-block;
  }
  .dept-user-page .paging {
    text-align: right;
    margin: 7px;
  }
</style>
